# -*- coding: utf-8 -*-
"""
字体配置模块
用于处理中文字体显示问题
"""

import os
import platform
from kivy.core.text import LabelBase
from kivy.logger import Logger
from kivy.utils import platform as kivy_platform

class FontManager:
    """字体管理器"""
    
    def __init__(self):
        self.chinese_font_registered = False
        self.fallback_font_registered = False
    
    def get_system_fonts(self):
        """获取系统字体路径列表"""
        # 使用kivy.utils.platform来检测平台
        current_platform = kivy_platform
        
        if current_platform == 'android':
            # Android系统字体 - 扩展更多可能的路径
            return [
                '/system/fonts/DroidSansFallback.ttf',  # 最常见的Android中文字体
                '/system/fonts/NotoSansCJK-Regular.ttc',
                '/system/fonts/NotoSansSC-Regular.otf',
                '/system/fonts/SourceHanSansSC-Regular.otf',
                '/system/fonts/NotoSansHans-Regular.otf',
                '/system/fonts/NotoSansCJK.ttc',
                '/system/fonts/Roboto-Regular.ttf',  # 备用
                '/system/fonts/DroidSans.ttf'  # 另一个备用
            ]
        elif os.name == 'nt' or current_platform == 'win':  # Windows
            return [
                'C:/Windows/Fonts/msyh.ttc',      # 微软雅黑
                'C:/Windows/Fonts/msyhbd.ttc',    # 微软雅黑粗体
                'C:/Windows/Fonts/simsun.ttc',    # 宋体
                'C:/Windows/Fonts/simhei.ttf',    # 黑体
                'C:/Windows/Fonts/arial.ttf'      # 备用
            ]
        elif current_platform == 'macosx':
            return [
                '/System/Library/Fonts/PingFang.ttc',  # macOS
                '/System/Library/Fonts/Helvetica.ttc',
                '/Library/Fonts/Arial.ttf'
            ]
        elif current_platform == 'linux' or os.name == 'posix':
            return [
                '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',  # Linux
                '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
                '/usr/share/fonts/TTF/DejaVuSans.ttf',
                '/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc'
            ]
        else:
            return []
    
    def register_chinese_font(self):
        """注册中文字体"""
        if self.chinese_font_registered:
            return True
        
        font_paths = self.get_system_fonts()
        
        for font_path in font_paths:
            if os.path.exists(font_path):
                try:
                    # 在Android上，尝试使用不同的注册方式
                    if kivy_platform == 'android':
                        # 对于Android，尝试注册为默认字体
                        LabelBase.register(name='Chinese', fn_regular=font_path)
                        # 同时注册为默认字体，确保所有组件都能使用
                        LabelBase.register(name='default', fn_regular=font_path)
                    else:
                        LabelBase.register(name='Chinese', fn_regular=font_path)
                    
                    Logger.info(f"FontManager: Successfully registered Chinese font: {font_path}")
                    self.chinese_font_registered = True
                    return True
                except Exception as e:
                    Logger.warning(f"FontManager: Failed to register font {font_path}: {e}")
                    continue
        
        Logger.warning("FontManager: No suitable Chinese font found")
        return False
    
    def register_fallback_font(self):
        """注册备用字体"""
        if self.fallback_font_registered:
            return True
        
        try:
            # 使用Kivy默认字体作为备用
            LabelBase.register(name='Fallback', fn_regular=None)
            self.fallback_font_registered = True
            Logger.info("FontManager: Fallback font registered")
            return True
        except Exception as e:
            Logger.error(f"FontManager: Failed to register fallback font: {e}")
            return False
    
    def get_font_name(self):
        """获取可用的字体名称"""
        if self.chinese_font_registered:
            return 'Chinese'
        elif self.fallback_font_registered:
            return 'Fallback'
        else:
            return None  # 使用系统默认字体
    
    def setup_fonts(self):
        """设置字体"""
        Logger.info("FontManager: Setting up fonts...")
        
        # 尝试注册中文字体
        if self.register_chinese_font():
            Logger.info("FontManager: Chinese font setup complete")
            return 'Chinese'
        
        # 如果中文字体注册失败，注册备用字体
        if self.register_fallback_font():
            Logger.info("FontManager: Fallback font setup complete")
            return 'Fallback'
        
        Logger.warning("FontManager: Using system default font")
        return None

# 全局字体管理器实例
font_manager = FontManager()

def setup_fonts():
    """设置字体的便捷函数"""
    return font_manager.setup_fonts()

def get_font_name():
    """获取字体名称的便捷函数"""
    return font_manager.get_font_name()